package com.aischool.api;

import com.aischool.common.kit.Md5Kit;
import com.aischool.common.model.AiOrg;
import com.aischool.common.model.AiTeacher;
import com.aischool.common.model.SysUser;
import com.aischool.params.AiOrgParams;
import com.aischool.routes.RouteMapping;
import com.aischool.service.AiAppArticleCatService;
import com.aischool.service.AiOrgService;
import com.aischool.service.AiTeacherService;
import com.aischool.service.SysUserAppService;
import com.aischool.service.SysUserRoleService;
import com.aischool.service.SysUserService;
import com.aischool.utils.AppUtil;
import com.aischool.utils.DateUtil;
import com.aischool.utils.JsonCodeEnum;
import com.aischool.utils.JsonResult;
import com.aischool.utils.RegexUtil;
import com.aischool.utils.StateEnum;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

@RouteMapping(url = "/api/aiorg")
public class AiOrgController extends Controller {
	
	@Inject
	AiOrgService aiOrgService;
	@Inject
	SysUserService sysUserService;
	@Inject
	SysUserAppService sysUserAppService;
	@Inject
	SysUserRoleService sysUserRoleService;
	@Inject
	AiTeacherService aiTeacherService;
	@Inject
	AiAppArticleCatService aiAppArticleCatService;

	public void getPage() {
		// 结果类
		JsonResult jr = new JsonResult();
		// 参数类
		AiOrgParams params = new AiOrgParams();
		// 获取参数
		params.setPageNo(getParaToInt("pageNo", 1));
		params.setPageSize(getParaToInt("pageSize", AppUtil.Default_PageSize));
//		if (getParaToInt("state")!=null) {
//			params.setState(getParaToInt("state"));
//		}
		params.setState(StateEnum.ALL.getState());
		if (StrKit.notBlank(get("keywords",""))) {
			params.setKeywords(get("keywords",""));
		}

		// 获取分页
		Object pageData = aiOrgService.getPage(params);
		
		jr.setDicKV("pageData", pageData);
		
		jr.setEnum(JsonCodeEnum.Success);
		renderJson(jr.Dic);
	}
	
	public void getOrg() {
		// 结果类
		JsonResult jr = new JsonResult();
		
		int org_id = getInt("id", 0);
		Object obj = aiOrgService.getOrg(org_id);
		if (obj != null) {
			jr.setDicKV("orginfo", obj);
		}
		
		jr.setEnum(JsonCodeEnum.Success);
		renderJson(jr.Dic);
	}
	
	public void save() {

		// 结果类
		JsonResult jr = new JsonResult();
		// 参数
		int org_id = getParaToInt("org_id", 0);
		int add_teacher = getParaToInt("add_teacher", 0);
		// 执行结果
		boolean bf = false;
		
		if (StrKit.isBlank(getPara("org_name",""))) {
			jr.appendMsg("请输入机构名称！");
		}else if (StrKit.isBlank(getPara("link_tel",""))) {
			jr.appendMsg("请输入机构热线！");
		}else if (StrKit.isBlank(getPara("area_names",""))) {
			jr.appendMsg("请选择省市县街道！");
		}else if (StrKit.isBlank(getPara("area_address",""))) {
			jr.appendMsg("请输入详细地址！");
		}else if (add_teacher == 1 && StrKit.isBlank(getPara("teacher_name",""))) {
			jr.appendMsg("请输入园长姓名！");
		}else if (add_teacher == 1 && StrKit.isBlank(getPara("teacher_mobile",""))) {
			jr.appendMsg("请输入园长手机！");
		}else if (add_teacher == 1 && !RegexUtil.isMobile(getPara("teacher_mobile"))) {
			jr.appendMsg("请输入正确的手机号码！");
		}else if (add_teacher == 1 && StrKit.isBlank(getPara("teacher_pwd",""))) {
			jr.appendMsg("请输入园长密码！");
		}else if (add_teacher == 1 && sysUserService.getUserByMobile(getPara("teacher_mobile"))!=null) {
			jr.appendMsg("该园长手机号码已注册！请更换手机号码！");
		}else {
			AiOrg info = getModel(AiOrg.class, "", true);	
			
			info.setClassOpen(null);
			info.setAddTime(null);
			info.setUpdateTime(DateUtil.getTimestamp());
			info.removeNullValueAttrs();
						
			if (add_teacher == 1) {
				AiTeacher infot = new  AiTeacher();
				SysUser infou = new SysUser();
				
				infot.setTeacherName(getPara("teacher_name"));
				infot.setTeacherMobile(getPara("teacher_mobile"));
				infot.setTeacherStateid(info.getOrgState());
				infot.setPostId(1); // 默认园长职务
				infot.setAddTime(DateUtil.getTimestamp());
				infot.setUpdateTime(DateUtil.getTimestamp());
				// 
				infot.setOrgId(org_id);
				infot.setUserId(0);
				
				infou.setLoginName(getPara("teacher_mobile"));
				infou.setLoginPwd(Md5Kit.MD5For8(getPara("teacher_pwd")));
				infou.setUserMobile(getPara("teacher_mobile"));
				infou.setUserName(getPara("teacher_name"));
				infou.setRegTime(DateUtil.getTimestamp());
				infou.setUpdateTime(DateUtil.getTimestamp());
				infou.setUserState(info.getOrgState());
				infou.setIsLock(false);
				
				
				
				bf = Db.tx(() -> {
						boolean bft = true; // 添加园长结果
						int user_id = 0;
						bft = infou.save();
						if (bft) {
							user_id = infou.getUserId();
							// 设置用户应用权限
							sysUserAppService.setUserApp(user_id, 4);
							// 设置用户应用角色
							sysUserRoleService.setUserAppRole(user_id, 4, 2);
							
							info.setAdminUserid(user_id);
							if (org_id >0) {
								// 更新
								bft = info.update();
							}else {
								// 插入
								info.setStartTime(DateUtil.getTimestamp());
								info.setAddTime(DateUtil.getTimestamp());
								bft = info.save();
								if (bft) {
									aiAppArticleCatService.setDefaultAppArticleCat(4, info.getOrgId());
								}
							}
							if (bft) {
								infot.setUserId(user_id);
								infot.setOrgId(info.getOrgId());
								bft = infot.save();
							}
						}
						return bft;
					});
				
			}else {
				if (org_id >0) {
					Record rdold = aiOrgService.getOrg(org_id);
					int old_userid = rdold.getInt("admin_userid");
					// 更新
					String teacher_pwd = get("teacher_pwd", "");
					String teacher_mobile = get("teacher_mobile", "");
					String teacher_name = get("teacher_name", "");
					
					boolean bfpwd = teacher_pwd.length()>0 ;
					boolean bfmobile = teacher_mobile.equals(rdold.get("teacher_mobile"));
					//boolean bfname = teacher_name.equals(rdold.get("teacher_name"));
					
					////////
					boolean bfnext = true;
					if (StrKit.isBlank(teacher_mobile)) {
						jr.setMsg("园长手机不能为空！");
						bfnext = false;
						
					}else if(StrKit.isBlank(teacher_name)) {
						jr.setMsg("园长姓名不能为空！");
						bfnext = false;
						
					}else if (bfmobile) {
						Record rdu = sysUserService.getUserByMobile(teacher_mobile);
						if (rdu != null && rdu.getInt("user_id") != old_userid) {
							jr.setMsg("手机号已注册！请更换手机号！");
							bfnext = false;
						}
					}
					if (bfnext) {
						SysUser infou = new SysUser();
						infou.setUserId(old_userid);
						infou.setUserState(info.getOrgState());
						infou.removeNullValueAttrs();
						if (bfpwd) {
							infou.setLoginPwd(Md5Kit.MD5For8(teacher_pwd));
						}
						if (!bfmobile) {
							infou.setLoginName(teacher_mobile);
							infou.setUserMobile(teacher_mobile);
						}
						
						//System.err.println(infou);
						
						bf = Db.tx(() -> {
							boolean bft = true; // 添加园长结果
							bft = aiTeacherService.updateInfo(old_userid, teacher_mobile, teacher_name, info.getOrgState());
							
							if (bft) {
								bft = infou.update();
							}
							if (bft) {
								bft = info.update();
							}
							return bft;
						});
						if (bf) {
							sysUserService.removeCache(old_userid);
						}
					}
				}else {
					// 插入
					info.setStartTime(DateUtil.getTimestamp());
					info.setAddTime(DateUtil.getTimestamp());
					bf = info.save();
					if (bf) {
						aiAppArticleCatService.setDefaultAppArticleCat(4, info.getOrgId());
					}
				}
			}
		}
		
		if (bf) {
			jr.setEnum(JsonCodeEnum.Success);
		}else {
			String msg = jr.getMsg();
			jr.setEnum(JsonCodeEnum.Faild);
			jr.appendMsg(msg);
		}

		renderJson(jr.Dic);
	}
	
	public void del() {
		// 结果类
		JsonResult jr = new JsonResult();
		
		boolean bf = false;
		// 表单转换类
		int org_id = getParaToInt("id", 0);
		if (org_id > 0) {
			bf = aiOrgService.del(org_id);
		}else {
			String ids = get("ids","");
			bf = aiOrgService.delMore(ids);
		}
		if (bf) {
			jr.setEnum(JsonCodeEnum.Success);
		}else {
			jr.setEnum(JsonCodeEnum.Faild);
		}
		renderJson(jr.Dic);
	}
}
